const db = require('../config/database');
const moment = require('moment');

class User {
  static async findAll(page = 1, limit = 10, searchParams = {}) {
    const offset = (page - 1) * limit;
    let query = 'SELECT * FROM user WHERE 1=1';
    const params = [];
    
    if (searchParams.id) {
      query += ' AND id = ?';
      params.push(searchParams.id);
    }
    if (searchParams.username) {
      query += ' AND username LIKE ?';
      params.push(`%${searchParams.username}%`);
    }
    if (searchParams.createAt) {
      query += ' AND createAt LIKE ?';
      params.push(`%${searchParams.createAt}%`);
    }
    
    query += ` LIMIT ${limit} OFFSET ${offset}`;
    
    return new Promise((resolve, reject) => {
      db.all(query, params, (err, rows) => {
        if (err) reject(err);
        resolve(rows);
      });
    });
  }

  static async count(searchParams = {}) {
    let query = 'SELECT COUNT(*) as total FROM user WHERE 1=1';
    const params = [];
    
    if (searchParams.id) {
      query += ' AND id = ?';
      params.push(searchParams.id);
    }
    if (searchParams.username) {
      query += ' AND username LIKE ?';
      params.push(`%${searchParams.username}%`);
    }
    if (searchParams.createAt) {
      query += ' AND createAt LIKE ?';
      params.push(`%${searchParams.createAt}%`);
    }

    return new Promise((resolve, reject) => {
      db.get(query, params, (err, row) => {
        if (err) reject(err);
        resolve(row.total);
      });
    });
  }

  static async create(userData) {
    const { username, password } = userData;
    const createAt = moment().format('YYYY-MM-DD HH:mm:ss');
    
    return new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO user (username, password, createAt) VALUES (?, ?, ?)',
        [username, password, createAt],
        function(err) {
          if (err) reject(err);
          resolve(this.lastID);
        }
      );
    });
  }

  static async update(id, userData) {
    const { username, password } = userData;
    
    return new Promise((resolve, reject) => {
      db.run(
        'UPDATE user SET username = ?, password = ? WHERE id = ?',
        [username, password, id],
        (err) => {
          if (err) reject(err);
          resolve(true);
        }
      );
    });
  }

  static async delete(id) {
    return new Promise((resolve, reject) => {
      db.run('DELETE FROM user WHERE id = ?', [id], (err) => {
        if (err) reject(err);
        resolve(true);
      });
    });
  }
}

module.exports = User; 